# -*- coding: UTF-8 -*-
import tushare as ts
import pandas as pd
import time,os,datetime,math,struct,sys
from colorama import init, Fore, Back, Style
# from makedir import FileOp
pd.set_option('display.expand_frame_repr', False)
init(autoreset=True)
from loguru import logger
currentDate = time.strftime("%Y%m%d", time.localtime())
LOG_DIR = os.path.expanduser("logs/")
LOG_FILE = os.path.join(LOG_DIR, currentDate+".log")
logger.add(LOG_FILE,rotation = "2000KB" , encoding='gb2312')   #压缩成zip格式
ts.set_token('531f7eda35d265a43c7091a5971802aab320a80c16afb6e7164c595a')
pro = ts.pro_api()

def init_list():
    logger.success("初始化股票代码")
    ''''
    is_hs	str	N	是否沪深港通标的，N否 H沪股通 S深股通
    list_status	str	N	上市状态 L上市 D退市 P暂停上市，默认是L
    exchange	str	N	交易所 SSE上交所 SZSE深交所 BSE北交所
    ts_code	str	N	TS股票代码
    market	str	N	市场类别 （主板/创业板/科创板/CDR/北交所）
    limit	int	N
    offset	int	N
    name	str	N	名称
    '''
    df = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date')
    df.to_csv("stocklist.csv")
    logger.success(df)
    # print(df)


def appexec(csvfilepath, funcxxx, **kwargs):
    logger.info("appexec")
    # stocklist, msg = STOCK.getlist()
    stocklist = csvfilepath
    scale = len(csvfilepath)
    logger.critical(str(scale))
    i = 0
    LL = 40
    for __list in stocklist:
        i += 1
        msg = ""#getattr(funcxxx, '__name__')
        # print("csvfilepath+__listcsvfilepath+__list",csvfilepath+__list)
        msg1, msg2 = funcxxx( __list, **kwargs)
        a = (i / scale) * 100
        # b = '.' * LL
        c = '▋' * (int((i * LL) / scale))
        b = '.' * ((LL - 1) - int((i * LL) / scale))
        dur = time.perf_counter()  # //每次获取当前时间
        msg1 = ""
        msg2=""
        print(Style.BRIGHT + Fore.RED + "\r[{}]{:^3.0f}% {}{} {:.2f}s".format(i, a, c, b, dur), '',
              Back.GREEN + msg, Fore.GREEN + 'MSG:' + msg1 + __list, end=' ')
        # time.sleep(0.01)
        # if i == 100:
        #     break
    print("循环", i)

currentDate = time.strftime("%Y%m%d", time.localtime())
def funcx(pathfile):
    # logger.info(pathfile)

    # print(currentDate)
    df = pro.daily(ts_code=pathfile, start_date='20220103', end_date=currentDate)
    exportfile="tushareData2/"+pathfile+".CSV"
    # print(exportfile)
    df.to_csv(exportfile)
    msg1 = "func"
    msg2 = pathfile
    return msg1, msg2

starttime = datetime.datetime.now()
logger.debug("开始调用funcxx函数。。。")


df = pd.read_csv("stocklist.csv")
logger.success(type(df["ts_code"]))
appexec(df["ts_code"].values.tolist(),funcxxx=funcx)

endtime = datetime.datetime.now()
logger.success('程序运行时间:'+ str(endtime - starttime))